# -*- coding: utf8 -*-
from soccerbots import tohexstr,strhex

MESSAGELEN = 300

class NetMessage:
    def __init__(self, type=None):
        self.type = type
        self.lines = []

    def append(self, line):
        self.lines.append(str(line))

    def appendValue(self, k, v):
        self.append(str(k)+': '+str(v))

    def pack(self):
        res = ''
        if self.type:
            res += self.type+'\n'
        res += '\n'.join(self.lines)+'\0'
        return res

    def numLines(self):
        return len(self.lines)
    
    def getLine(self, num):
        parts = self.lines[num].split(':')
        k = parts[0].strip()
        v = ':'.join(parts[1:]).strip()
        return k,v  

    @staticmethod
    def parseMessage(message):
        parts = message.split('\n')
        msg = NetMessage(parts[0])
        for part in parts[1:]:
            msg.append(part)
        return msg

class BotsSocket:
    def __init__(self, socket):
        self.s = socket

    def readMessage(self):
        data = self.s.recv(MESSAGELEN)
        if not data:
            print 'Socket destroyed'
            raise RuntimeError
        data = data.split('\0')[0]
        lines = data.split('\n')
        msg = NetMessage(lines[0])
        for line in lines[1:]:
            msg.append(line)
        return msg

    def readPlainMessage(self):
        data = self.s.recv(MESSAGELEN)
        if not data:
            print 'Socket destroyed'
            raise RuntimeError
        data = data.split('\0')[0]
        lines = data.split('\n')
        msg = NetMessage()
        for line in lines:
            msg.append(line)
        return msg

    def sendMessage(self, msg, to=None):
        data = msg.pack()
        data += '#'*(MESSAGELEN - len(data))
        if to!=None:
            self.s.sendto(data, to)
        else:
            self.s.send(data)

    def getSource(self):
        return self.s.getpeername()
